<script setup>
import router from '@/router'
import { ref, onMounted } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores/index'
import { userLoginService, addUserService, rememberPasswordService } from '@/api/user'
const time = ref(new Date().toLocaleTimeString())
const date = ref(new Date().toLocaleDateString())
const captchaUrl = ref('')
const isRegister = ref(false)
const form = ref()
const formModel = ref({
  name: '',
  password: '',
  code: '',
  key: 0,
  jzmm: false
})
const registerForm = ref({
  name: '',
  password: '',
  repassword: ''
})
formModel.value.key = Math.random()
captchaUrl.value = baseURL + '/captcha?key=' + formModel.value.key
setInterval(() => {
  time.value = new Date().toLocaleTimeString()
  date.value = new Date().toLocaleDateString()
}, 1000)

const rules = {
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码为 4 位', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z\u4e00-\u9fa5][a-zA-Z0-9_\u4e00-\u9fa5]{2,9}$/,
      message: '用户名以字母开头，包含字母、数字、下划线',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
    {
      pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)(?!.*\s)[0-9A-Za-z]{6,16}$/,
      message: '密码至少包含字母、数字、特殊字符，不能包含空格，长度在 6 到 16 个字符',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
    {
      pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)(?!.*\s)[0-9A-Za-z]{6,16}$/,
      message: '密码至少包含字母、数字、特殊字符，不能包含空格，长度在 6 到 16 个字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
//记住密码
const rememberPassword = () => {
  const user = userStore.user
  if (user.jzmm === '1') {
    formModel.value.name = user.name
    formModel.value.password = user.password
    formModel.value.jzmm = true
  }
}
onMounted(() => {
  rememberPassword()
})
//刷新验证码
const refreshCaptcha = () => {
  formModel.value.key = Math.random()
  captchaUrl.value = baseURL + '/captcha?key=' + formModel.value.key
}
const userStore = useUserStore()
const login = async () => {
  await form.value.validate()
  formModel.value.jzmm = formModel.value.jzmm === false ? '0' : '1'
  const res = await userLoginService(formModel.value)

  console.log(formModel.value)
  if (res.code == 0) {
    userStore.setToken(res.data.token)
    await userStore.getUser(res.data.id)
    userStore.user.jzmm = formModel.value.jzmm
    console.log(userStore.user)

    await rememberPasswordService(userStore.user)
    await ElMessage.success('登录成功')
    router.push('/')
  } else {
    ElMessage.error('登录失败，请检查用户名,密码或验证码')
    refreshCaptcha()
  }
}

const register = async () => {
  await form.value.validate()
  console.log(registerForm.value)

  await addUserService(registerForm.value)
  ElMessage.success('注册成功')
  isRegister.value = false
}
</script>
<template>
  <div class="bg">
    <!-- 标题 -->
    <div class="title">游戏服务管理系统</div>
    <!-- 登录/注册表单 -->
    <div class="form-container">
      <el-col :span="24" class="form">
        <el-form
          :model="registerForm"
          :rules="rules"
          ref="form"
          size="large"
          autocomplete="off"
          v-if="isRegister"
        >
          <el-form-item>
            <div class="flex">
              <h1>注册</h1>
              <el-link type="primary" :underline="false" @click="isRegister = false">
                ← 返回
              </el-link>
            </div>
          </el-form-item>
          <el-form-item prop="name">
            <el-input
              v-model="registerForm.name"
              :prefix-icon="User"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
              v-model="registerForm.password"
            ></el-input>
          </el-form-item>
          <el-form-item prop="repassword">
            <el-input
              v-model="registerForm.repassword"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入再次密码"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="register" class="button" type="primary" auto-insert-space>
              注册
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 登录表单 -->
        <el-form
          :model="formModel"
          :rules="rules"
          ref="form"
          size="large"
          autocomplete="off"
          v-else
        >
          <el-form-item>
            <div class="flex">
              <h1>登录</h1>
              <el-link type="primary" :underline="false" @click="isRegister = true">
                注册 →
              </el-link>
            </div>
          </el-form-item>
          <el-form-item prop="name" label="账号:">
            <el-input
              :prefix-icon="User"
              placeholder="请输入用户名"
              v-model="formModel.name"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码:">
            <el-input
              name="password"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
              v-model="formModel.password"
            ></el-input>
          </el-form-item>
          <!-- 验证码 -->
          <el-form-item prop="code">
            <div class="flex">
              <img :src="captchaUrl" alt="验证码" @click="refreshCaptcha" />
              <div>验证码</div>
              <el-input
                placeholder="请输入验证码"
                v-model="formModel.code"
                style="width: 50%; height: 40px"
                @keyup.enter="login"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item class="flex">
            <div class="flex">
              <el-checkbox v-model="formModel.jzmm" label="记住密码" size="large" />
              <el-link type="primary" :underline="false">忘记密码？</el-link>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button @click="login()" class="button" type="primary" auto-insert-space
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <!-- 时间显示 -->
    <div class="clock">
      <div class="time">{{ time }}</div>
      <div class="date">{{ date }}</div>
    </div>
    <div class="copy">CopyRight©2024 WWW.xiaofeitu.com All Right Reserved</div>
    <div class="logo">
      <img src="../../assets/logo.png" alt="" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.bg {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0px;
  left: 0px;
  /* 渐变 */
  background-image: url('../../assets/login1.jpg');
  background-size: 100%;
  animation: move 60s infinite linear;
}

@keyframes move {
  0% {
    background-position: 0% 100%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 100%;
  }
}

.title {
  font-size: 70px;
  font-weight: 500;
  position: absolute;
  left: 5%;
  top: 10%;
  color: transparent;
  /* 文字颜色透明 */
  background: linear-gradient(to right, red, orange, yellow, green, cyan, blue, purple);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: hue 30s linear infinite;
}

@keyframes hue {
  0% {
    filter: hue-rotate(0deg);
  }

  100% {
    filter: hue-rotate(360deg);
  }
}

.clock {
  background-color: rgba(11, 83, 160, 0.2);
  border-radius: 10px;
  color: aliceblue;
  position: absolute;
  top: 80%;
  left: 3%;
  text-align: right;

  .time {
    font-size: 50px;
  }

  .date {
    font-size: 35px;
  }
}

.copy {
  color: aliceblue;
  position: absolute;
  bottom: 3%;
  left: 35%;
  right: 0;
}

// 登录/注册表单
.form-container {
  width: 400px;
  height: 420px;
  position: absolute;
  background-color: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(1px);
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 20px;
}

.form {
  margin-left: 20px;
  margin-right: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  user-select: none;

  .title {
    margin: 0 auto;
  }

  .button {
    width: 100%;
  }

  .flex {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}

// 图标
.logo {
  position: absolute;
  bottom: 5%;
  right: 0%;

  img {
    width: 300px;
  }
}
</style>
